package ebcs.scan.controller.userCtr;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

import ebcs.database.bean.BsGroupInfor;
import ebcs.database.bean.BsProTeamInfor;
import ebcs.database.bean.BsUserDetailInfo;
import ebcs.database.bean.BsUserInfor;
import ebcs.database.bean.RpUserTaskNeedBean;
import ebcs.database.bean.SysFunction;
import ebcs.database.service.BsGroupInforServiceImp;
import ebcs.database.service.BsProTeamServiceImp;
import ebcs.database.service.BsUserInforServiceImp;
import ebcs.database.service.BsUserNeedServiceImp;
import ebcs.database.service.PaUserRoleServiceImp;
import ebcs.database.service.SystemServiceImp;
import ebcs.scan.common.consts.KLinkUsSysConsts;
import ebcs.scan.common.consts.UserStatus;
import ebcs.scan.common.utils.HttpClientUtil;
import ebcs.scan.common.utils.MD5Util;
import ebcs.scan.common.utils.Properties;
import ebcs.scan.common.utils.StringUtil;
import ebcs.scan.controller.batch.BatchManagerCtrl;
import ebcs.scan.service.wechat.WechatCtrlService;
import jplat.core.session.JSession;
import jplat.core.trans.JAppBaseService;
import jplat.core.trans.JAppContext;
import jplat.core.trans.JAppContextFactory;
import jplat.error.exception.JSystemException;
import jplat.error.exception.JTransException;
import jplat.tools.config.JAppConfig;
import jplat.tools.string.DateUtil;
import jplat.tools.string.JRandomUtil;


/***
 * 用户基本信息
 * @author chenzhuo
 * @comment
 */
@Controller
public class UserManagerCtrl extends JAppBaseService {
    private Logger logger = Logger.getLogger(UserManagerCtrl.class);


    protected JAppContextFactory serviceFactory = new JAppContextFactory();


    //数据库库服务.
    @Autowired
    public BsUserInforServiceImp userInforService;

    @Autowired
    private BsUserNeedServiceImp userNeedService;
    @Autowired
    public BsProTeamServiceImp teamService;

    @Autowired
    public BsGroupInforServiceImp groupService;

    @Autowired
    public SystemServiceImp systemService;
    @Autowired
    public WechatCtrlService wechatService;
    
    @Autowired
    public PaUserRoleServiceImp paUserRoleServiceImp;
    @Autowired
    BatchManagerCtrl batch;
    @Autowired
	public BsGroupInforServiceImp bsGroupInfoServiceImp;

    public static String CHARSET_ENCODING = "UTF-8";

    /**
     * 后台管理登录
     * @param request
     * @param response
     * @param session
     * @throws IOException 
     * @throws JTransException 
     */
    @RequestMapping("/page/sys/adminLogin.do")
    public void adminLogin(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IOException, JTransException{
    	String phoneNo = request.getParameter("phoneNo");
    	String password = request.getParameter("password");
    	
    	//登录用户的手机号码与密码不能为空
    	if(phoneNo == null || "".equals(phoneNo)){
    		throw new JTransException("1001", "手机号码不能为空。");
    	}
    	if(password == null || "".equals(password)){
    		throw new JTransException("1001", "密码不能为空。");
    	}
    	//根据手机号码与密码查询数据库对应的数据
    	List<BsUserInfor> list = userInforService.adminLogin(phoneNo, new MD5Util().getMD5ofStr(password));
    	if(list != null && list.size() > 0){
    		//根据userrouid查询团队经理的信息
    		//List<BsGroupInfor> bsGroupInfors = groupService.selectGroupByUserRouid(list.get(0).getRouid());
    		//if(bsGroupInfors == null || bsGroupInfors.size() <= 0){
    		//	throw new JTransException("415", "权限不足无法进入后台管理界面。");
    		//}
            try {
            	BsUserInfor user =  list.get(0);
            	user.setLoginType(KLinkUsSysConsts.USER_LOGIN_TYPE_BACK);//后台登录
				doPushUserTaskInfor(request, response,user);
			} catch (JSystemException e) {
 				e.printStackTrace();
				logger.error("login error:"+e.getErrMsg());
			}// 返回客户待办任务信息

    		throw new JTransException("200", "success");
    	}else{
    		throw new JTransException("1001", "手机号码或者密码不正确。");
    	}
    }
    /**
     * 用户注册跳转
     */
    @RequestMapping("/page/sys/regUser.do")
    public String regUser(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
    	List<BsProTeamInfor> teanList =  teamService.searchProTeanList();
		List<BsGroupInfor> groupList = this.groupService.searchGroupList();
		request.setAttribute("teanList", teanList);
		request.setAttribute("groupList", groupList);
        return "frame/html/user/regUser";
    }
    

    /**
     * 用户注册
     */
    @RequestMapping("/page/sys/doRegUser.do")
    public void doRegUser(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        BsUserInfor user = context.obtainReqModel(BsUserInfor.class);
        //判断该手机号是否重复
        BsUserInfor userBean = this.userInforService.selectUserInforByPhoneNo(user.getPhoneNo());
        if (userBean != null) {
        	//判断用户是否为注册状态 如果是注册状态的话就修改用户信息
        	if(userBean.getState() != null && "02".equals(userBean.getState())){
        		user.setUserNo(userBean.getUserNo());
        		int row = this.userInforService.updateUserByUserNo(user);
        		if(row != 0){
        			//发送审核信息给团队经理
                    batch.sendRegApplytoGroupUser(user.getProGroupNo(), user.getProTeamNo(), user.getUserName());
        			Map rspModel = new HashMap();
        	        context.buildAppResponse(rspModel);
        		}
        	}
        	
            throw new JTransException("1001", "你的手机号已经注册了吧，赶紧到登陆页面试试！");
        }


        user.setRouid(JRandomUtil.getUUID());
        	
        String userNo = this.userInforService.selectUserMaxNoByTeamNo(user);
        logger.info("userMaxNo:" + userNo);
        user.setUserNo(userNo);
        user.setCreateDate(DateUtil.getSystemTimeBySomeFormat("yyyyMMdd"));
        user.setCreateTime(DateUtil.getSystemTimeBySomeFormat("hh:mm:ss"));
        user.setState(KLinkUsSysConsts.USER_STATE_VERIFY);//设置为审核状态
        int i = this.userInforService.insertUserInfor(user);
        //发送审核信息给团队经理
        batch.sendRegApplytoGroupUser(user.getProGroupNo(), user.getProTeamNo(), user.getUserName());
        if (i == 0) {
            throw new JTransException("1001", "添加用户信息失败了。");
        }
       
        Map rspModel = new HashMap();
        context.buildAppResponse(rspModel);
    }


    /**
     * 查询用户所在团队的项目组
     *
     * @param request
     * @param response
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/base/searchTeanByUser.do")
    public String searchTeanByUser(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextWithUser(request, response);        //buildAppContextWithUser 自带客户信息.
        BsUserInfor userBean = context.getUserInfo();
        List<BsProTeamInfor> teanList = this.teamService.searchProTeanListByGroupNo(userBean.getProGroupNo());
        request.setAttribute("teanList", teanList);
        RpUserTaskNeedBean condition = new RpUserTaskNeedBean();
        condition.setProGroupNo(userBean.getProGroupNo());
        List<RpUserTaskNeedBean> taskList = this.userNeedService.selectTaskNeedListByGroupNo(condition);
        request.setAttribute("taskList", taskList);
        return "frame/html/user/receiveTask";
    }


    //用户后台管理
    //1、用户信息查询
    @RequestMapping("/page/sys/searchUserInfor.do")
    public void searchUserInfor(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        BsUserDetailInfo user = context.obtainReqModel(BsUserDetailInfo.class);
        String endRow = ((Integer.parseInt(user.getStartRow()))+(Integer.parseInt(user.getPageSize())))+"";
        user.setEndRow(endRow);
        int count=userInforService.selectUserDetailCount(user);
        List<BsUserDetailInfo> userDetailInfoList = userInforService.selectUserDetailPage(user);
        Map rsModel = new HashMap();
		rsModel.put("count", count);
  		rsModel.put("userList", userDetailInfoList);
 		context.buildAppResponse(rsModel);
    }

    //2、添加用户信息
    @RequestMapping("/page/sys/addUserInfor.do")
    public void addUserInfor(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        BsUserInfor user = context.obtainReqModel(BsUserInfor.class);
        Map rspModel = new HashMap();
        context.buildAppResponse(rspModel);
    }

    //3、注销用户
    public void logoutUserInfor(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        BsUserInfor user = context.obtainReqModel(BsUserInfor.class);
        Map rspModel = new HashMap();
        context.buildAppResponse(rspModel);
    }

    /**
     * 4.修改用户状态信息
     * 1.当用户状态改为无效时设置用户的注销时间，否则则去掉用户的注销时间
     * @param request
     * @param response
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/sys/updateUserStatus.do")
    public void updateUserStatus(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        BsUserInfor user = context.obtainReqModel(BsUserInfor.class);
        if(user != null && "00".equals(user.getState())){
        	//System.out.println("---------------ccc");
        	user.setLogoffDate(new Date());
        }
        userInforService.updateUserStatus(user);
        Map rspModel = new HashMap();
        context.buildAppResponse(rspModel);
    }

    //5 根据userNo查询用户
    @RequestMapping("/page/sys/{userNo}/selectSingleUser.do")
    public String selectSingleUser(HttpServletRequest request, HttpServletResponse response, @PathVariable String userNo) throws JTransException, JSystemException {
        BsUserDetailInfo user = new BsUserDetailInfo();
        user.setUserNo(userNo);
        List<BsUserDetailInfo> detailInfoList = userInforService.selectUserDetail(user);
        if (!CollectionUtils.isEmpty(detailInfoList)) {
            request.setAttribute("user", detailInfoList.get(0));
        }
        request.setAttribute("teanList", teamService.searchProTeanList());
        request.setAttribute("userStatus", UserStatus.values());
        return "main/report/updateUser";
    }

    @RequestMapping("/page/sys/updateUser.do")
    public void updateUser(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);//自动客户信息
        BsUserInfor user = context.obtainReqModel(BsUserInfor.class);
        if (StringUtils.isNotBlank(user.getPhoneNo())) {
            List<BsUserInfor> userInforList = this.userInforService.selectUserInforsByPhoneNo(user.getPhoneNo());
            if (!CollectionUtils.isEmpty(userInforList)) {
                for (BsUserInfor bsUserInfor : userInforList) {
                    if (bsUserInfor.getUserNo().equals(user.getUserNo())) {
                        continue;
                    }
                    throw new JTransException("1001", "手机号重复了！");
                }
            }
        }
        if(user != null && "00".equals(user.getState())){
        	//System.out.println("---------------ccc");
        	user.setLogoffDate(new Date());
        }
        if(user != null && "01".equals(user.getState())){
        	user.setPassDate(new Date());
        }
        int i = this.userInforService.updateUserByUserNo(user);
        if (i == 0) {
            throw new JTransException("1001", "更新用户信息失败了。");
        }
        Map rspModel = new HashMap();
        context.buildAppResponse(rspModel);
    }

    /**
     * 不使用微信openid 登陆
     *
     * @param request
     * @param response
     * @return
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/login/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws JTransException, JSystemException {
        request.setAttribute("wechatUrl", "0");//微信打开不做校验
        try{
        	Object obj =  session.getAttribute("loginUser");
        	if(obj != null && obj instanceof BsUserInfor){
        		BsUserInfor user = (BsUserInfor)obj;
        		//通过rouid置空用户的openid;
        		int row = userInforService.updateOpenidtoNullByRouid(user.getRouid());
        		//System.out.println(row != 0?">>>>>修改成功！":">>>>>修改失败");
        	}
        }catch(Exception ex){
        	ex.printStackTrace();
        }
        return "frame/html/user/login";
    }

    /**
     * 微信登录
     *
     * @param request
     * @param response
     * @return
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/login/loginWechat.do")
    public String doLoginWechat(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {

        String code = request.getParameter("code");
        if (StringUtil.isNotEmpty(code)) {
            logger.info("wechat----->code:" + code);
            String openid = "";
            JAppContext context = serviceFactory.buildAppContextWithUser(request, response);        //buildAppContextWithUser 自带客户信息.
            BsUserInfor sessionUser = context.getUserInfo();
            String wechatBackJson = HttpClientUtil.htmlstr(wechatService.getUserInfoByCode(code));
            logger.info("wechatBackJson:" + wechatBackJson);
            Gson gson = new Gson();
            Map tokenGsonMap = gson.fromJson(wechatBackJson, HashMap.class);
            openid = String.valueOf(tokenGsonMap.get("openid"));
            
            logger.info("loginWechat:" + openid);
            request.setAttribute("openid", openid);
            request.setAttribute("wechatUrl", "0");
            BsUserInfor user = this.userInforService.selectUserInforByOpenid(openid);
            if (user != null) {
            	user.setLoginType(KLinkUsSysConsts.USER_LOGIN_TYPE_WECHAT);
                doPushUserTaskInfor(request, response, user);//拉取客户信息
                if(user.getState() == null || "02".equals(user.getState())){
                	request.setAttribute("errorMsg","该用户正在审核中，"
                			+ "注册的团队是：“"+user.getProGroupName()+"”，"
                			+ "注册的项目组是：“"+user.getProTeamName()+"”，"
                			+ "请尽快联系团队经理进行审核，如果信息填写错误请使用该号码进行重新注册");
                	return "error";
                }else if(user.getState() == null || "00".equals(user.getState())){
                	request.setAttribute("errorMsg","该用户已经被注销。");
                	return "error";
                }
                return "frame/html/user/index";
            }
        } else {
            request.setAttribute("wechatBackJson", "空");
            try {
                String wechatUrl = wechatService.buildAuthorizeUrl(JAppConfig.APP_URL + "/page/login/loginWechat.do", JAppConfig.APP_URL + "/page/login/loginWechat.do");
                request.setAttribute("wechatUrl", wechatUrl);
            } catch (IOException e) {
                logger.error("buildAuthorizeUrl e:" + e.getMessage());
                e.printStackTrace();
            }
        }
        return "frame/html/user/login";
    }
    
    
    
    
    
    

    /**
     * 返回客户待办任务信息
     */
    public String doPushUserTaskInfor(HttpServletRequest request, HttpServletResponse response, BsUserInfor user) throws JTransException, JSystemException {
        JSession session;
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);        //buildAppContextWithUser 自带客户信息.
        session = context.createSession(true);
        session.setUserInfo(user);
       
       
        
        if(KLinkUsSysConsts.USER_LOGIN_TYPE_WECHAT.equals(user.getLoginType())) {
        	RpUserTaskNeedBean condition = new RpUserTaskNeedBean();
            condition.setUserNo(user.getUserNo());
            List<RpUserTaskNeedBean> taskList = this.userNeedService.selectTaskNeedList(condition);
            List<RpUserTaskNeedBean> noTaskList = this.userNeedService.selectNoTaskNeedList(condition);
        	request.setAttribute("taskList", taskList);
            request.setAttribute("taskSize", taskList.size());
            request.setAttribute("noTaskList", noTaskList);
            request.setAttribute("noTaskSize", noTaskList.size());
            List<SysFunction> funcList = systemService.selectFunction(user);
            request.setAttribute("funcList", funcList);
        }
        
        request.setAttribute("userName", user.getUserName());
        request.getSession().setAttribute("loginUserName", user.getUserName());
        request.getSession().setAttribute("loginUser", user);
        request.setAttribute("state", user.getState());
        System.out.println("-------------------"+user.getPosition_type()+"-------------------------");
        System.out.println("-------------------"+user.getProTeamNo()+"-------------------------");
        if(user.getPosition_type()!=null&&user.getProTeamNo()!=null){
        	//因为要根据不同的用户的情况查询bsGroupInfors,所以分为下面这几种情况
        	
        	//2.如果职位为69并且不是人事的
	        if(user.getPosition_type().equals("69")&&!user.getProTeamNo().equals("103")){
	         List<BsGroupInfor> bsGroupInfors = groupService.selectGroupByUserRouid(user.getRouid());
	         request.getSession().setAttribute("loginGroupInfo", bsGroupInfors);
	        } else {//3.职位为其他如70
	        	List<BsGroupInfor> bsGroupInfors = groupService.selectProGroupNoByUserNo(user.getUserNo());
	        	request.getSession().setAttribute("loginGroupInfo", bsGroupInfors);
	        }
        }else{
        	//4.加上判断走到这里是为了前台登录不报错
        	 List<BsGroupInfor> bsGroupInfors = groupService.selectGroupByUserRouid(user.getRouid());
	         request.getSession().setAttribute("loginGroupInfo", bsGroupInfors);
        }
        return session.getSessionID();
    }

    /**
       * 获取用户菜单权限
     *
     * @param request
     * @param response
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/sys/getUserFuncList.do")
    public void getUserFuncList(HttpServletRequest request, HttpServletResponse response)throws JTransException, JSystemException  {
        JAppContext context = serviceFactory.buildAppContextWithUser(request, response);        //buildAppContextWithUser 自带客户信息.
        BsUserInfor user = context.getUserInfo();
        user.setLoginType(KLinkUsSysConsts.USER_LOGIN_TYPE_BACK);
    	//得到原userno,position_type
        String userNo=user.getUserNo();
        String position_type = user.getPosition_type();
        request.setAttribute("position_type", position_type);
        List<SysFunction> funcList =null;
       /* //财务的同志可以有所有的权限 ,但权限是根据userNo判断,所以现在暂时的吧财务的userNo改为大老板的
     /*   if(user.getProTeamNo().equals("101")){
    		user.setUserNo("0001");
    	}*/
        /*if("68".equals(position_type)){
        if(user.getProTeamNo().length()>=3){
	        String ptn=user.getProTeamNo().substring(0,3);
	        if("103".equals(ptn)){//人力资源的同事为了访问108项目成本导入的权限,暂时把userNo和positiontype设置为黄静的
	        	user.setUserNo("0013");
	        	user.setPosition_type("68");
	        }
	        
	         funcList = systemService.selectFunction(user);
	         @SuppressWarnings("unused")
			List<SysFunction> newFuncList =new ArrayList<SysFunction>();
	        if("68".equals(position_type)&&!"103".equals(ptn)&&!"101".equals(ptn)){
	        	//将职位是68但不是人力资源的同志的项目成本导入功能权限去掉
	        	for (int i = 0; i < funcList.size(); i++) {
					if("108".equals(funcList.get(i).getFuncId())){
						funcList.remove(i);
					}
				}
	        }else if("68".equals(position_type)&&"103".equals(ptn)) {
	        	//将职位是人力资源的同志的權限放入到新的集合
	        	for (int i = 0; i < funcList.size(); i++) {
	        		String funcId=funcList.get(i).getFuncId();
					if("108".equals(funcId)||
							"10801".equals(funcId)||
							"103".equals(funcId)||
							"10303".equals(funcId)||
							"104".equals(funcId)||
							"10402".equals(funcId)||
							"10406".equals(funcId)||
							"105".equals(funcId)||
							"10501".equals(funcId)||
							"10502".equals(funcId)){
						newFuncList.add(funcList.get(i));
					}
				}
	        }else if("68".equals(position_type)&&"101".equals(ptn)) {
	        	//将职位是財務的同志的權限放入到新的集合
	        	for (int i = 0; i < funcList.size(); i++) {
	        		String funcId=funcList.get(i).getFuncId();
					if("104".equals(funcId)||"10406".equals(funcId)||"10407".equals(funcId)){
						newFuncList.add(funcList.get(i));
					}
				}
	        }
	      //得到权限后将userNo,position_type还原
            user.setUserNo(userNo);
            user.setPosition_type(position_type);
            Map rsMap = new HashMap();
            rsMap.put("user", user);
            rsMap.put("funcList", newFuncList);
            context.buildAppResponse(rsMap);
        }
        }else{*/
            funcList = systemService.selectFunction(user);
            //得到权限后将userNo,position_type还原
            user.setUserNo(userNo);
            user.setPosition_type(position_type);
            Map rsMap = new HashMap();
            rsMap.put("user", user);
            rsMap.put("funcList", funcList);
            context.buildAppResponse(rsMap);
        /*}*/
    }

    /**
     * 用于登录
     *
     * @param request
     * @param response
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/base/dologin.do")
    public String doLogin(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        //1、获取用户信息手机号 查询用户信息
        String phoneNo = request.getParameter("phoneNo");
        String openid = request.getParameter("openid");
        logger.info("login openid-->" + openid);
        if (StringUtil.isEmpty(phoneNo)) {
            JAppContext context = serviceFactory.buildAppContextWithUser(request, response);        //buildAppContextWithUser 自带客户信息.
            BsUserInfor user = context.getUserInfo();
            phoneNo = user.getPhoneNo();
        }
        //2、如果存在就登陆成功，返回用户基本信息，所属项目组，姓名等...
        BsUserInfor user = this.userInforService.selectUserInforByPhoneNo(phoneNo);
        if (user != null) {
        	user.setLoginType(KLinkUsSysConsts.USER_LOGIN_TYPE_WECHAT);
            doPushUserTaskInfor(request, response, user);// 返回客户待办任务信息
            if (StringUtil.isNotEmpty(openid)) {
            	
                this.userInforService.updateUserOpenIdByPhoneNo(openid, phoneNo);
            }
            if(user.getState() == null || "02".equals(user.getState())){
            	request.setAttribute("errorMsg","该用户正在审核中，"
            			+ "注册的团队是：“"+user.getProGroupName()+"”，"
            			+ "注册的项目组是：“"+user.getProTeamName()+"”，"
            			+ "请尽快联系团队经理进行审核，如果信息填写错误请使用该号码进行重新注册");
            	return "error";
            }else if(user.getState() == null || "00".equals(user.getState())){
            	request.setAttribute("errorMsg","该用户已经被注销。");
            	return "error";
            }
            return "frame/html/user/index";
        } else {
            request.setAttribute("errorMsg", "手机号码错误！<br/>温馨提示:<br/>请确认手机号码与企业微信注册号码相同");
            return "error";
        }
        //3、失败弹出登陆失败，提示无此用户信息
    }


    /**
     * 手机号登陆鉴权
     *
     * @param request
     * @param response
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/login/{phoneNo}/dologin.do")
    public void doLoginV2(HttpServletRequest request, HttpServletResponse response, @PathVariable String phoneNo) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);        //buildAppContextWithUser 自带客户信息.
        //2、如果存在就登陆成功，返回用户基本信息，所属项目组，姓名等...
        BsUserInfor user = this.userInforService.selectUserInforByPhoneNo(phoneNo);
        JSession session;
        session = context.createSession(true);
        session.setUserInfo(user);
        Cookie sessCookie = new Cookie("JSESSIONID", session.getSessionID());//为了和浏览器兼容.
        sessCookie.setPath("/");
        response.addCookie(sessCookie);
        context.buildAppResponse(null);
        //3、失败弹出登陆失败，提示无此用户信息
    }


    /**
     * 用于登录 新登陆
     *
     * @param request
     * @param response
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/base/V1/dologin.do")
    public void doLoginV1(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);        //buildAppContextWithUser 自带客户信息.
        BsUserInfor req = context.obtainReqModel(BsUserInfor.class);
        //1、获取用户信息手机号 查询用户信息
        //2、如果存在就登陆成功，返回用户基本信息，所属项目组，姓名等....
        BsUserInfor user = this.userInforService.selectUserInforByPhoneNo(req.getPhoneNo());
        if (user != null) {
            Map rsMol = new HashMap();
            rsMol.put("userInfor", user);
            rsMol.put("sysDate", DateUtil.getSystemTimeBySomeFormat("yyyyMMdd"));
            context.buildAppResponse(rsMol);
            return;
        } else {
            throw new JTransException("1001", "该用户不存在，请确认后再登陆！");
        }
    }

    /*
     * 微信自身用户信息
     * @param request
     * @return 返回商户编号、门店信息、金额 等。
     */
    @RequestMapping(value = "/ns0/eQrPay/getWechatUserInfor.do")
    public String getWechatUserInfor(HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");
        if (StringUtil.isNotEmpty(code)) {
            logger.info("wechat----->code:" + code);
            String wechatBackJson = HttpClientUtil.htmlstr(wechatService.getUserInfoByCode(code));
            logger.info("wechatBackJson:" + wechatBackJson);
            Gson gson = new Gson();
            Map tokenGsonMap = gson.fromJson(wechatBackJson, HashMap.class);
            String openid = String.valueOf(tokenGsonMap.get("openid"));
            request.setAttribute("openid", openid);
            request.setAttribute("wechatBackJson", wechatBackJson);
            request.setAttribute("wechatUrl", "0");
        } else {
            request.setAttribute("wechatBackJson", "空");
            try {
                String wechatUrl = wechatService.buildAuthorizeUrl(Properties.getString("Static_ctx") + "ns0/eQrPay/getWechatUserInfor.do", Properties.getString("Static_ctx") + "ns0/eQrPay/getWechatUserInfor.do");
                request.setAttribute("wechatUrl", wechatUrl);
            } catch (IOException e) {
                logger.error("buildAuthorizeUrl e:" + e.getMessage());
                e.printStackTrace();
            }
        }
        return "mpage/eQrPay/wechatInfo";
    }


    /**
     * 用于微信小程序
     *
     * @param request
     * @param response
     * @throws JTransException
     * @throws JSystemException
     */
    @RequestMapping("/page/applet/doLoginApplet.do")
    public void doLoginApplet(HttpServletRequest request, HttpServletResponse response) throws JTransException, JSystemException {
        //1、获取用户信息手机号 查询用户信息
        JAppContext context = serviceFactory.buildAppContextNoUser(request, response);        //buildAppContextWithUser 自带客户信息.

        BsUserInfor userBean = context.obtainReqModel(BsUserInfor.class);
        //2、如果存在就登陆成功，返回用户基本信息，所属项目组，姓名等....
        BsUserInfor user = this.userInforService.selectUserInforByPhoneNo(userBean.getPhoneNo());
        if (user != null) {
            JSession session;
            try {
                session = context.createSession(true);
                session.setUserInfo(user);
                Map rsMap = new HashMap();
                rsMap.put("user", user);
                context.buildAppResponse(rsMap);
            } catch (JSystemException e) {
                e.printStackTrace();
                throw new JTransException("1001", "手机号码错误！<br/>温馨提示:<br/>请确认手机号码与企业微信注册号码相同");
            }
        } else {
            throw new JTransException("1001", "手机号码错误！<br/>温馨提示:<br/>请确认手机号码与企业微信注册号码相同");
        }
    }
    
    /**
     * 查询出某个团队下所有未通过审批的注册用户
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/page/main/selectNoPassRegUserByRouid.do")
    public String selectNoPassRegUserByRouid(HttpServletRequest request,HttpServletResponse response) throws IOException{
    	String rouid = request.getParameter("rouid");
    	List<BsUserDetailInfo> bsUserDetailInfos = userInforService.selectNoPassRegUserByRouid(rouid);
    	request.setAttribute("noPassRegUserList", bsUserDetailInfos);
    	return "main/report/regUserPass";
    }
    
    
    /**
     * 修改密码
     * @param request
     * @param response
     * @throws JSystemException 
     * @throws IOException
     * @throws Exception 
     */
    @RequestMapping("/page/main/updatePassWord.do")
    @ResponseBody
    public void updatePassWord(HttpServletRequest request,HttpServletResponse response){
    	try{
    	JAppContext context = serviceFactory.buildAppContextNoUser(request, response);        //buildAppContextWithUser 自带客户信息.
        BsUserInfor user = context.obtainReqModel(BsUserInfor.class);
        //判断页面输入的原密码和数据库的密码是否相同
        String pwd=new MD5Util().getMD5ofStr(user.getPwd());
        if(!pwd.equals(user.getUpassWord())){
        	context.buildAppResponse("False");
        	return;
        }
        //相同的话将页面输入的新密码加密后存入数据库
       user.setConfirmPwd(new MD5Util().getMD5ofStr(user.getConfirmPwd()));
       userInforService.updatePassWord(user);
       context.buildAppResponse("OK");;
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	
    }
    
    /**
     * 修改密码
     * @param request
     * @param response
     * @throws IOException
     * @throws Exception 
     */
    @RequestMapping("/page/main/updPassWord.do")
    public String updPassWord(HttpServletRequest request,HttpServletResponse response) throws IOException, Exception{
    	JAppContext context = serviceFactory.buildAppContextWithUser(request,response);		//buildAppContextWithUser 自带客户信息.
		BsUserInfor user = context.getUserInfo();
		request.setAttribute("userBean", user);
//		String rouid = user.getRouid();
//		BsUserInfor userInfor = userInforService.selectUserInforByUserNo(rouid);
//		request.setAttribute("oldPassWord", userInfor.getUpassWord());
    	return "frame/html/user/updPass";
    }
}
